package view;

import controller.LoginController;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginView extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginButton;

    public LoginView() {
        setTitle("Pizza Ordering System - Login");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(3, 2));

        panel.add(new JLabel("Username:"));
        usernameField = new JTextField();
        panel.add(usernameField);

        panel.add(new JLabel("Password:"));
        passwordField = new JPasswordField();
        panel.add(passwordField);

        loginButton = new JButton("Login");
        panel.add(new JLabel()); // Placeholder
        panel.add(loginButton);

        add(panel);

        // Add Action Listener
        loginButton.addActionListener(e -> {
            String username = usernameField.getText();
            String password = new String(passwordField.getPassword());
            // 从数据库中获取用户角色
            String role = "user";
            ;// 默认角色为用户
            LoginController controller = new LoginController();
            boolean success = controller.login(username, password);
            if (success) {
                if ("admin".equals(username)) {

                    // 跳转到管理员界面
                    // 这里需要添加代码来实现界面跳转
                    new AdminView().setVisible(true);
                    dispose(); // 关闭当前登录界面
                } else if ("user".equals(role)) {

                    // 跳转到点单页面
                    // 这里需要添加代码来实现界面跳转
                    new CustomerView(username).setVisible(true);
                    dispose(); // 关闭当前登录界面
                } else {
                    JOptionPane.showMessageDialog(null, "Invalid role!");
                }
            } else {

                JOptionPane.showMessageDialog(null, "Login failed!");
            }

        });

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new LoginView().setVisible(true);
        });
    }
}
